<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\admin\middleware;

use app\merwap\model\Menu;
use app\merwap\model\Merchant;
use app\merwap\model\MerchantAdmin;
use app\merwap\model\Role;
use think\Request;
use Throwable;

class AdminUserMiddleware
{

    /**
     * @param Request $request
     * @param \Closure $next
     * @return $this|mixed
     */
    public function handle(Request $request,\Closure $next)
    {
        try {
            $merAdminId = request()->adminId;
            $merId = request()->mer_id;
            $mer = Merchant::where('mer_id', $merId)->field('mer_id')->find();
            // 如果存在商户数据，则判断为超管
            if ($mer) {
                return $next($request);
            }
            $merAdmin = MerchantAdmin::where('merchant_admin_id', $merAdminId)->find();
            $rolesArray = explode(',', $merAdmin['roles']);
            if (empty($rolesArray)) {
                return json()->data(['code'=>411,'msg'=>'您没有权限访问','data'=>[]]);
            }
            // 查询角色
            $roles = Role::where(['status' => 1, 'mer_id' => $merAdmin['mer_id']])
                ->whereIn('role_id', $rolesArray)
                ->column('rules');
            if (empty($roles)) {
                return json()->data(['code'=>411,'msg'=>'您没有权限访问','data'=>[]]);
            }
            $menuArray = [];
            foreach ($roles as $rv) {
                $arr = explode(',', $rv);
                $menuArray = array_merge($menuArray, $arr);
            }
            // 去重
            $menuArray = array_unique($menuArray);
            // 查询权限
            $auth = Menu::whereIn('menu_id', $menuArray)
                ->column('route');
            $currRoute = request()->rule()->getName();
            if (in_array($currRoute, $auth)) {
                return $next($request);
            } else {
                return json()->data(['code'=>411,'msg'=>'您没有权限访问','data'=>[]]);
            }
        } catch (Throwable $e) {
            return json()->data(['code'=>428,'msg'=>'请求发生错误，请重试','data'=>[]]);
        }
    }

}